<template>
  <div>
    <el-row v-if="canEditSku">
      <el-col>
        <el-button :disabled="skuFormData.extral.length >= maxSkuCount" type="primary" icon="el-icon-plus" @click="addSku">添加附加规格</el-button>
      </el-col>
    </el-row>
    <el-form ref="form" :model="skuFormData" label-position="right" label-width="110px">
      <el-row v-for="(sku, skuIndex) in skuFormData.extral" :key="skuIndex" class="sku-item">
        <el-col :span="24">
          <el-form-item
            :label="'规格名 '+ (skuIndex + 1) + ':'"
            :prop="'extral.' + skuIndex + '.name'"
            style="padding-bottom: 20px"
            :rules="[
              {
                required: true, validator: validSku , trigger: 'change'}
            ]"
          >
            <el-col :span="24">
              <el-input v-model="sku.name" :disabled="!canEditSku" placeholder="请输入规格名，例如：必选配件、咨询服务" maxlength="10" style="max-width: 400px;" />
              <el-button v-if="canEditSku" style="margin-left: 15px;" type="danger" icon="el-icon-delete" @click="deleteSku(skuIndex)">删除</el-button>
            </el-col>
          </el-form-item>
          <el-form-item
            label="规格描述:"
            :rules="[
              {
                required: true, validator: validDesc , trigger: 'change'}
            ]"
            :prop="'extral.' + skuIndex + '.desc'"
            style="padding-bottom: 20px"
          >
            <el-col :span="24">
              <el-input v-model="sku.desc" :disabled="!canEditSku" placeholder="请输入规格描述，例如：请选择要增加的配件" maxlength="20" style="max-width: 400px;" />
            </el-col>
          </el-form-item>
          <el-form-item
            label="规格类型:"
            :prop="'extral.' + skuIndex + '.type'"
            style="padding-bottom: 20px"
          >
            <el-col :span="24">
              <el-radio-group v-model="sku.type" @change="changeSkuType(skuIndex)">
                <el-radio-button label="custom">商品</el-radio-button>
                <el-radio-button label="online">在线服务</el-radio-button>
              </el-radio-group>
            </el-col>
          </el-form-item>
          <el-form-item
            label="是否必选:"
            :prop="'extral.' + skuIndex + '.mustSelect'"
            style="padding-bottom: 20px"
          >
            <el-col :span="24">
              <el-radio-group v-model="sku.mustSelect">
                <el-radio-button :label="0">可选</el-radio-button>
                <el-radio-button :label="1">必选</el-radio-button>
              </el-radio-group>
            </el-col>
          </el-form-item>
          <el-form-item
            label="是否多选:"
            :prop="'extral.' + skuIndex + '.multiSelFlg'"
            style="padding-bottom: 20px"
          >
            <el-col :span="24">
              <el-radio-group v-model="sku.multiSelFlg">
                <el-radio-button :label="0">单选</el-radio-button>
                <el-radio-button :label="1">多选</el-radio-button>
              </el-radio-group>
            </el-col>
          </el-form-item>
          <el-form-item>
            <el-button v-if="canEditSku" :disabled="sku.values.length >= maxSpecCount" type="primary" icon="el-icon-plus" @click="addSpec(skuIndex)">添加规格值</el-button>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-table
            :data="sku.values"
            border
            style="margin-top: 20px; width: 100%; margin-bottom: 10px;"
          >
            <el-table-column
              type="index"
              :resizable="false"
              width="50"
              label="序号"
              align="center"
            />
            <el-table-column
              v-if="sku.type == 'custom'"
              label="规格值"
              align="center"
              :resizable="false"
              width="320"
            >
              <template slot-scope="scope">
                <el-form-item
                  label-width="0px"
                  style="padding: 15px 0;"
                  :rules="[
                    { validator: validSpec1 , trigger: 'change'}
                  ]"
                  :prop="'extral.' + skuIndex + '.values.' + scope.$index + '.value'"
                >
                  <el-input v-model="scope.row.value" clearable :disabled="!canEditSku" placeholder="请输入规格值，例如：坐垫" maxlength="10" style="width: 100%;" />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column
              v-else-if="sku.type == 'online'"
              label="规格值"
              align="center"
              :resizable="false"
              width="320"
            >
              <template slot-scope="scope">
                <el-form-item
                  label-width="0px"
                  style="padding: 15px 0;"
                  :rules="[
                    { validator: validSpec2 , trigger: 'change'}
                  ]"
                  :prop="'extral.' + skuIndex + '.values.' + scope.$index + '.value'"
                >
                  <el-input v-model="scope.row.value" clearable :disabled="!canEditSku" placeholder="请输入规格值，例如：制氧机在线服务" maxlength="10" style="width: 100%;" />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column
              label="规格类型"
              align="center"
              :resizable="false"
              width="100"
            >
              <template>
                <el-tag v-if="sku.type == 'custom'" type="info">商品</el-tag>
                <el-tag v-else-if="sku.type == 'online'" type="info">在线服务</el-tag>
                <el-tag v-else type="info">未知</el-tag>
              </template>
            </el-table-column>
            <el-table-column
              v-if="sku.type == 'custom'"
              align="center"
              label="关联商品"
              :resizable="false"
              min-width="250"
            >
              <template slot-scope="scope">
                <ExtendsGoodsInfo :goods-id="scope.row.commodityid" />
              </template>
            </el-table-column>
            <el-table-column
              v-else-if="sku.type == 'online'"
              align="center"
              label="关联在线服务"
              :resizable="false"
              min-width="250"
            >
              <template slot-scope="scope">
                <ExtendsServiceInfo :service-id="scope.row.commodityid" />
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              width="230"
              :resizable="false"
              label="操作"
              fixed="right"
            >
              <template slot-scope="scope">
                <el-button v-if="sku.type == 'custom'" type="primary" @click="showSelectGoods(skuIndex, scope.$index)">
                  <template v-if="scope.row.commodityid">重选商品</template>
                  <template v-else>选择商品</template>
                </el-button>
                <el-button v-else-if="sku.type == 'online'" type="primary" @click="showSelectService(skuIndex, scope.$index)">
                  <template v-if="scope.row.commodityid">重选服务</template>
                  <template v-else>选择服务</template>
                </el-button>
                <el-button v-if="canEditSku && sku.values.length > 1" type="danger" icon="el-icon-delete" @click="deleteSpec(skuIndex, scope.$index)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>

        </el-col>
      </el-row>
    </el-form>

    <SelectGoodsDialog ref="selectGoodsDialog" @select="onSelectGoods" />
    <SelectServiceDialog ref="selectServiceDialog" @select="onSelectService" />
  </div>
</template>

<script>
import ExtendsGoodsInfo from '../ExtendsGoodsInfo/index'
import { Message } from 'element-ui'
import SelectGoodsDialog from '@/components/SelectGoodsDialog'
import SelectServiceDialog from '@/components/SelectServiceDialog'
import ExtendsServiceInfo from '../ExtendsServiceInfo/index'
export default {
  name: 'ExtendsSku',
  components: { ExtendsServiceInfo, SelectGoodsDialog, ExtendsGoodsInfo, SelectServiceDialog },
  props: {
    canEditSku: {
      type: Boolean,
      default: true
    },
    skuFormData: {
      type: Object,
      default() {
        return {
          extral: []
        }
      }
    }
  },
  data() {
    return {
      validSku: (rule, value, callback) => {
        if (value === undefined || value == null || value.trim().length <= 0) {
          Message.closeAll()
          Message.error('附加规格名不能为空')
          callback(new Error('请输入规格名'))
          return
        }
        let count = 0
        this.skuFormData.extral.forEach(sku => {
          if (sku.name === value) {
            count++
          }
        })
        if (count > 1) {
          Message.closeAll()
          Message.error('附加规格名【' + value + '】重复，请修改')
          callback(new Error('规格名重复，请修改'))
          return
        }
        callback()
      },
      validDesc: (rule, value, callback) => {
        if (value === undefined || value == null || value.trim().length <= 0) {
          Message.closeAll()
          Message.error('附加规格描述不能为空')
          callback(new Error('请输入规格描述'))
          return
        }
        callback()
      },
      validSpec1: (rule, value, callback) => {
        if (value === undefined || value == null || value.trim().length <= 0) {
          Message.closeAll()
          Message.error('附加规格值不能为空')
          callback(new Error('请输入规格值'))
          return
        }
        let count = 0
        this.skuFormData.extral[rule.fullField.split('.')[1]].values.forEach(spec => {
          if (spec.value === value) {
            count++
          }
        })
        if (count > 1) {
          Message.closeAll()
          Message.error('附加规格值【' + value + '】重复，请修改')
          callback(new Error('规格值重复，请修改'))
          return
        }
        if (!this.skuFormData.extral[rule.fullField.split('.')[1]].values[rule.fullField.split('.')[3]].commodityid) {
          Message.closeAll()
          Message.error('附加规格值【' + value + '】未选择关联商品')
          callback(new Error('请选择关联商品'))
          return
        }
        callback()
      },
      validSpec2: (rule, value, callback) => {
        if (value === undefined || value == null || value.trim().length <= 0) {
          Message.closeAll()
          Message.error('附加规格值不能为空')
          callback(new Error('请输入规格值'))
          return
        }
        let count = 0
        this.skuFormData.extral[rule.fullField.split('.')[1]].values.forEach(spec => {
          if (spec.value === value) {
            count++
          }
        })
        if (count > 1) {
          Message.closeAll()
          Message.error('附加规格值【' + value + '】重复，请修改')
          callback(new Error('规格值重复，请修改'))
          return
        }
        if (!this.skuFormData.extral[rule.fullField.split('.')[1]].values[rule.fullField.split('.')[3]].commodityid) {
          Message.closeAll()
          Message.error('附加规格值【' + value + '】未选择关联在线服务')
          callback(new Error('请选择关联在线服务'))
          return
        }
        callback()
      },
      // 最多允许添加几个SKU规格
      maxSkuCount: 6,
      // 每个规格最多允许添加几个规格值
      maxSpecCount: 5,
      isValidate: false,
      tempSkuIndex: null,
      tempSpecIndex: null
    }
  },
  methods: {
    getData() {
      const vm = this

      if (!vm.skuFormData.extral || vm.skuFormData.extral.length <= 0) {
        return null
      }

      const res = vm.$XEUtils.clone(vm.skuFormData.extral, true)
      res.forEach(sku => {
        if (sku.specInfoId === -1) {
          delete sku.specInfoId
        }
        sku.values.forEach(spec => {
          if (sku.type === 'custom') {
            delete spec.goods
          } else if (sku.type === 'online') {
            delete spec.service
          }
          if (spec.productId === -1) {
            delete spec.productId
          }
        })
      })
      return res
    },
    showSelectGoods(skuIndex, specIndex) {
      this.tempSkuIndex = skuIndex
      this.tempSpecIndex = specIndex
      this.$refs.selectGoodsDialog.show()
    },
    showSelectService(skuIndex, specIndex) {
      this.tempSkuIndex = skuIndex
      this.tempSpecIndex = specIndex
      this.$refs.selectServiceDialog.show()
    },
    onSelectGoods(goods) {
      if (goods) {
        this.skuFormData.extral[this.tempSkuIndex].values[this.tempSpecIndex].commodityid = goods.goodsId
        this.skuFormData.extral[this.tempSkuIndex].values[this.tempSpecIndex].goods = goods
      }
      this.$refs.form.validateField('extral.' + this.tempSkuIndex + '.values.' + this.tempSpecIndex + '.value')
    },
    onSelectService(service) {
      if (service) {
        this.skuFormData.extral[this.tempSkuIndex].values[this.tempSpecIndex].commodityid = service.id
        this.skuFormData.extral[this.tempSkuIndex].values[this.tempSpecIndex].service = service
      }
      this.$refs.form.validateField('extral.' + this.tempSkuIndex + '.values.' + this.tempSpecIndex + '.value')
    },
    validate() {
      this.$refs.form.validate((valid) => {
        this.isValidate = valid
      })
      return this.isValidate
    },
    fixNumber(val, index, key) {
      if (val === undefined) {
        this.skuTableData[index][key] = -100000
      }
      this.$forceUpdate()
    },
    addSku() {
      this.skuFormData.extral.push({
        specInfoId: -1,
        name: '',
        type: 'custom',
        mustSelect: 0,
        multiSelFlg: 0,
        desc: '',
        values: [{
          productId: -1,
          value: null,
          commodityid: null,
          goods: null,
          service: null
        }]
      })
    },
    deleteSku(skuIndex) {
      this.skuFormData.extral.splice(skuIndex, 1)
    },
    addSpec(skuIndex) {
      this.skuFormData.extral[skuIndex].values.push({
        productId: -1,
        value: null,
        commodityid: null,
        goods: null,
        service: null
      })
    },
    deleteSpec(skuIndex, specIndex) {
      this.skuFormData.extral[skuIndex].values.splice(specIndex, 1)
    },
    changeSkuType(skuIndex) {
      const values = this.$XEUtils.clone(this.skuFormData.extral[skuIndex].values, true)
      values.forEach(item => {
        item.commodityid = null
        item.goods = null
        item.service = null
      })
      this.skuFormData.extral[skuIndex].values = values
      this.$refs.form.clearValidate()
      this.$forceUpdate()
    }
  }
}
</script>

<style scoped lang="scss">
  .sku-item {
    margin-top: 15px;
    padding: 15px;
    border: 1px solid #eeeeee;
  }
</style>
